#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import logging
import servicemanager
import win32serviceutil
import win32service
import win32event
import socket

# 设置日志
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'app_service.log')

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_file, encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger('app_service')

# 确保工作目录正确
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# 导入FastAPI应用
try:
    from app import app
    import uvicorn
    import configparser
    logger.info("成功导入FastAPI应用")
    
    # 创建start_app函数，因为原始app.py中没有此函数
    def start_app():
        """启动FastAPI应用的辅助函数"""
        try:
            # 读取服务配置
            config_parser = configparser.ConfigParser()
            port = 8000
            host = "0.0.0.0"
            log_level = "info"
            
            if os.path.exists('config.ini'):
                config_parser.read('config.ini', encoding='utf-8')
                if 'Service' in config_parser:
                    port = config_parser.getint('Service', 'port', fallback=8000)
                    host = config_parser.get('Service', 'host', fallback="0.0.0.0")
                    log_level = config_parser.get('Service', 'log_level', fallback="info")
            
            # 确保必要的目录存在
            os.makedirs("print_status", exist_ok=True)
            os.makedirs("static", exist_ok=True)
            os.makedirs("watch_folder", exist_ok=True)
            os.makedirs("logs", exist_ok=True)
            
            # 修复Windows服务环境中sys.stdout为None的问题
            # 这会导致uvicorn日志格式化器失败
            log_config = None
            if hasattr(sys, 'frozen') or sys.stdout is None:
                # 运行为服务或冻结可执行文件时，使用自定义日志配置
                log_config = {
                    "version": 1,
                    "disable_existing_loggers": False,
                    "formatters": {
                        "default": {
                            "()": "uvicorn.logging.DefaultFormatter",
                            "use_colors": False,
                        },
                        "access": {
                            "()": "uvicorn.logging.AccessFormatter",
                            "use_colors": False,
                        },
                    },
                    "handlers": {
                        "default": {
                            "formatter": "default",
                            "class": "logging.FileHandler",
                            "filename": os.path.join(log_dir, "uvicorn.log"),
                        },
                        "access": {
                            "formatter": "access",
                            "class": "logging.FileHandler",
                            "filename": os.path.join(log_dir, "uvicorn_access.log"),
                        },
                    },
                    "loggers": {
                        "uvicorn": {"handlers": ["default"], "level": "INFO"},
                        "uvicorn.error": {"level": "INFO"},
                        "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
                    },
                }
            
            # 启动应用
            logger.info(f"启动FastAPI服务器 {host}:{port}")
            uvicorn.run(app, host=host, port=port, log_level=log_level, log_config=log_config)
            
        except Exception as e:
            logger.error(f"启动应用失败: {e}")
            import traceback
            logger.error(traceback.format_exc())
    
except Exception as e:
    logger.error(f"导入应用失败: {e}")
    import traceback
    logger.error(traceback.format_exc())

class AppService(win32serviceutil.ServiceFramework):
    _svc_name_ = "CloudPrintApp"
    _svc_display_name_ = "云打印应用服务"
    _svc_description_ = "提供云打印功能的Web界面服务"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)
        self.is_running = False
        logger.info("服务初始化完成")

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.is_running = False
        logger.info("服务停止中...")

    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, '')
        )
        self.is_running = True
        logger.info("服务开始运行")
        
        try:
            # 启动FastAPI应用
            logger.info("正在启动FastAPI应用...")
            # 使用非阻塞方式启动应用
            import threading
            app_thread = threading.Thread(target=start_app, daemon=True)
            app_thread.start()
            logger.info("应用已在后台线程启动")
            
            # 主循环保持服务运行
            while self.is_running:
                # 检查是否收到停止信号
                if win32event.WaitForSingleObject(self.hWaitStop, 1000) == win32event.WAIT_OBJECT_0:
                    break
                # 30秒打印一次心跳日志
                logger.debug("服务运行中...")
                time.sleep(30)
                
        except Exception as e:
            logger.error(f"服务运行时出错: {e}")
            import traceback
            logger.error(traceback.format_exc())
            self.is_running = False

        logger.info("服务已停止")

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(AppService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(AppService) 